package com.xkcyy.one.ai.trainable.tools;

import com.fasterxml.jackson.databind.JsonNode;
import com.xkcyy.one.ai.common.tool.AbstractTool;
import com.xkcyy.one.ai.llm.model.ToolDefinition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

/**
 * 搜索工具实现
 * 
 * @author yuand
 */
@Slf4j
public class SearchTool extends AbstractTool {
    private final RestTemplate restTemplate;

    public SearchTool(ToolDefinition definition, RestTemplate restTemplate) {
        super(definition);
        this.restTemplate = restTemplate;
    }

    @Override
    protected String executeInternal(String inputParams) {
        try {
            JsonNode params = objectMapper.readTree(inputParams);
            String query = params.get("query").asText();
            String engine = params.get("engine").asText();

            String url = String.format("https://api.search.com/search?q=%s&engine=%s",
                    query, engine);

            String response = restTemplate.getForObject(url, String.class);
            return response;
        } catch (Exception e) {
            log.error("Error executing search tool", e);
            throw new RuntimeException("Failed to execute search tool", e);
        }
    }

    @Override
    public String getType() {
        return "search";
    }
}